package com.xd.core.company.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.base.CustomRowHeightColWidthHandler;
import com.xd.common.base.RowHeightColWidthModel;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.SecurityUtil;
import com.xd.core.api.mapper.ChannelPayTowMapper;
import com.xd.core.company.entity.OfflineTransferInfo;
import com.xd.core.company.mapper.ChannelTowRechargeMapper;
import com.xd.core.company.mapper.OfflineTransferInfoMapper;
import com.xd.core.company.service.IOfflineTransferInfoService;
import com.xd.core.finance.dto.PlatformRecordsDto;
import com.xd.core.finance.dto.PreDepositeQueryChannelTwoDto;
import com.xd.core.finance.dto.PreDepositeQueryDto;
import com.xd.core.finance.vo.PlatformRecordsVo;
import com.xd.core.finance.vo.PreDepositeQueryChannelTwoVo;
import com.xd.core.finance.vo.PreDepositeQueryVo;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 线下打款记录 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-03-03
 */
@Service
public class OfflineTransferInfoServiceImpl extends ServiceImpl<OfflineTransferInfoMapper, OfflineTransferInfo> implements IOfflineTransferInfoService {

    @Autowired
    private OfflineTransferInfoMapper offlineTransferInfoMapper;
    @Autowired
    private ISysUserService iSysUserService;
    @Value("${image.localPathDir}")
    private String localPathDir;
    @Value("${image.exportFile}")
    private String exportFile;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Value("${aes.key}")
    private String aesKey;
    @Autowired
    private ChannelTowRechargeMapper channelTowRechargeMapper;
    @Autowired
    private ChannelPayTowMapper channelPayTowMapper;

    /**
     * @description: 债权方账户-充值记录(平台资方共用)
     * @author: ZCH
     * @date: 2025/3/6 0006 16:20
     * @param: [preDepositeQueryDto]
     * @return: com.github.pagehelper.Page<com.xd.core.finance.vo.PreDepositeQueryVo>
     **/
    @Override
    public Page<PreDepositeQueryVo> getPreDepositRecord(PreDepositeQueryDto preDepositeQueryDto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = null;
        List<Integer> userIds = null;
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE) || companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)) {
            companyId = preDepositeQueryDto.getCompanyId();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_TOW)) {
            companyId = SecurityUtil.getLoginCompanyId();
            userIds = iSysUserService.getUserIdsByGroup();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_THREE)) {//代理
            return null;
        }
        //开始分页
        PageHelper.startPage(preDepositeQueryDto.getPageNum(), preDepositeQueryDto.getPageSize());
        return offlineTransferInfoMapper.getPreDepositRecord(preDepositeQueryDto, companyId);
    }

    /**
     * @description: 债权方账户充值记录导出
     * @author: ZCH
     * @date: 2025/3/25 0025 9:35
     * @param: [dto, id]
     * @return: void
     **/
    @Override
    public void exportPreDepositRecord(PreDepositeQueryDto dto, Integer id) {
        String name = "通道一充值提现记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 6, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 7, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);
            ExcelWriter write = EasyExcel.write(fileOutputStream, PreDepositeQueryVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            dto.setPageSize(0);
            List<PreDepositeQueryVo> list = getPreDepositRecord(dto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * @description 渠道二充值提现记录
     * @author Zch
     * @date 17:46 2025/7/7 星期一
     * @return com.github.pagehelper.Page<com.xd.core.finance.vo.PreDepositeQueryChannelTwoVo>
     **/
    @Override
    public Page<PreDepositeQueryChannelTwoVo> getPreDepositRecordChannelTwo(PreDepositeQueryChannelTwoDto preDepositeQueryDto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        Integer companyId = null;
        List<Integer> userIds = null;
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE) || companyType.equals(SysConstant.USER_COMPANY_TYPE_FOUR)) {
            companyId = preDepositeQueryDto.getCompanyId();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_TOW)) {
            companyId = SecurityUtil.getLoginCompanyId();
            userIds = iSysUserService.getUserIdsByGroup();
        } else if (companyType.equals(SysConstant.USER_COMPANY_TYPE_THREE)) {//代理
            return null;
        }
        //开始分页
        PageHelper.startPage(preDepositeQueryDto.getPageNum(), preDepositeQueryDto.getPageSize());
        //判断是充值还是提现
        if (preDepositeQueryDto.getType().equals("1")) {
            //获取充值记录
            Page<PreDepositeQueryChannelTwoVo> voRecharge = channelTowRechargeMapper.getRechargeRecord(preDepositeQueryDto, companyId);
            return voRecharge;
        } else {
            //获取提现记录
            Page<PreDepositeQueryChannelTwoVo> voReflect = channelPayTowMapper.getReflectRecord(preDepositeQueryDto, companyId);
            return voReflect;
        }
    }

    @Override
    public void exportPreDepositRecordChannelTwo(PreDepositeQueryChannelTwoDto dto, Integer id) {
        String name = "官方通道（标准）充值提现记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);
            ExcelWriter write = EasyExcel.write(fileOutputStream, PreDepositeQueryChannelTwoVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            dto.setPageSize(0);
            List<PreDepositeQueryChannelTwoVo> list = getPreDepositRecordChannelTwo(dto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /***
     * @description 平台提现记录
     * @author Zch
     * @date 14:27 2025/8/5 星期二
     * @return com.github.pagehelper.Page<com.xd.core.finance.vo.PlatformRecordsVo>
     **/
    @Override
    public Page<PlatformRecordsVo> getPlatformRecords(PlatformRecordsDto dto) {
        String companyType = SecurityUtil.getLoginUser().getUser().getCompanyType();
        if (companyType.equals(SysConstant.USER_COMPANY_TYPE_ONE)) {
            dto.setCompanyId(SysConstant.SUPER_COMPANY_ID);
        } else {
            return null;
        }
        //开始分页
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return channelPayTowMapper.getPlatformRecords(dto);
    }

    /***
     * @description 平台提现记录导出
     * @author Zch
     * @date 14:46 2025/8/5 星期二
     * @return void
     **/
    @Override
    public void exportPlatformRecords(PlatformRecordsDto dto, Integer id) {
        String name = "官方通道（标准）平台提现记录excel文件" + UUID.randomUUID().toString().replace("-", "");
        Integer companyId = SecurityUtil.getLoginCompanyId();
        FileOutputStream fileOutputStream = null;
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setId(id);
        missionCenterInfo.setFileName(name + ".xlsx");

        String filePath = localPathDir + exportFile + "/" + companyId;
        File dirFile = new File(filePath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        try {
            List<RowHeightColWidthModel> rowHeightColWidthList = new ArrayList<>();
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 0, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 1, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 2, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 3, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 4, 20));
            rowHeightColWidthList.add(RowHeightColWidthModel.createColWidthModel(name, 5, 20));
            File file = new File(filePath + "/" + name + ".xlsx");
            fileOutputStream = new FileOutputStream(file);
            ExcelWriter write = EasyExcel.write(fileOutputStream, PlatformRecordsVo.class).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(name).registerWriteHandler(new CustomRowHeightColWidthHandler(rowHeightColWidthList)).build();
            dto.setPageSize(0);
            List<PlatformRecordsVo> list = getPlatformRecords(dto);
            write.write(list, writeSheet);
            write.finish();
            fileOutputStream.flush();
            //修改文件状态 导出成功
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_TOW);
            missionCenterInfo.setFileUrl(exportFile + "/" + companyId + "/" + name + ".xlsx");
            missionCenterInfoMapper.updateById(missionCenterInfo);
        } catch (Exception e) {
            //修改文件状态 导出失败
            missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_THREE);
            missionCenterInfoMapper.updateById(missionCenterInfo);
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
